package org.vectrics.site.hosted;

import java.util.Date;

import javax.servlet.jsp.JspException;

import org.apache.log4j.Logger;
import org.vectrics.SystemException;
import org.vectrics.common.html.BorderTable;
import org.vectrics.common.html.Cell;
import org.vectrics.common.html.Row;
import org.vectrics.common.html.Table;
import org.vectrics.common.html.email.HtmlEmailHelper;
import org.vectrics.company.Company;
import org.vectrics.company.CompanyPerson;
import org.vectrics.company.CompanyPersonRoleType;
import org.vectrics.company.Sector;
import org.vectrics.domain.Domain;
import org.vectrics.hibernate.ThreadProperties;
import org.vectrics.mail.MailMessage;
import org.vectrics.mail.NotificationManager;
import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.user.PasswordEncryptor;
import org.vectrics.user.Person;
import org.vectrics.user.User;

/**
 * Save potential customer application for hosted contract.
 * 
 * @author Mike Moore
 */
public class SaveHostedApplication extends VectricsStrutsAction {
    private transient Logger log = Logger.getLogger(this.getClass());

    public SaveHostedApplication() {
        super();
    }

    /**
     * Do the action.
     */
    protected String doExecute(VectricsActionData actionData) throws JspException {
        log.info("doExecute() - starting");
        HostedApplicationForm form = (HostedApplicationForm) actionData.getForm();
        Domain domain = CoreServiceLocator.getSystemService().findSystemDomain();
        ThreadProperties.setSystemUser(true);
        ThreadProperties.setDomain(domain);
        ThreadProperties.setPerson(CoreServiceLocator.getConfiguration().getSystemPerson());

        Person person = new Person();
        person.setFirstName(form.getFirstName());
        person.setLastName(form.getLastName());
        person.setDomain(domain);
        person.setLocale("en");
        CoreServiceLocator.getPersonService().updatePerson(person);

        User user = person.createUserIfNotExist();
        user.setUserName(form.getEmail());
        user.setPassword(form.getPassword());
        user.setPasswordEncrypted(false);
        CoreServiceLocator.getPersonService().updatePerson(person);

        person.createContactInfoIfNotExist().setEmail(form.getEmail());
        CoreServiceLocator.getPersonService().updatePerson(person);

        Sector sector = CoreServiceLocator.getCompanyService().findSector(form.getSectorCode());
        if (sector == null)
            throw new SystemException("Could not find sector with code: " + form.getSectorCode());

        Company company = new Company();
        company.setName(form.getCompanyName());
        company.setDomain(domain);
        company.setSector(sector);
        CoreServiceLocator.getCompanyService().updateCompany(company);

        CompanyPerson companyPerson = new CompanyPerson();
        companyPerson.setCompany(company);
        companyPerson.setPerson(person);
        CoreServiceLocator.getCompanyService().updateCompanyPerson(companyPerson);

        companyPerson.addRole(CoreServiceLocator.getCompanyService().findCompanyPersonRoleType(
                CompanyPersonRoleType.ROLE_EMPLOYEE), new Date());
        CoreServiceLocator.getCompanyService().updateCompanyPerson(companyPerson);

        HostedApplication application = new HostedApplication();
        application.setCompany(company);
        application.setPerson(person);
        application.setDateSubmitted(new Date());
        ThreadProperties.getSession().save(application);
        ThreadProperties.forcedCommit();

        sendConfirmationEmail(domain, person, application);

        log.info("doExecute() - finished");
        return ("success");
    }

    /**
     * Send the email to request user to confirm hosting setup.
     * 
     * @param domain
     * @param person
     * @param application
     */
    private void sendConfirmationEmail(Domain domain, Person person, HostedApplication application) {

        MailMessage mailMessage = new MailMessage(domain);
        HtmlEmailHelper emailHelper = CoreServiceLocator.getHtmlEmailHelper();

        BorderTable mainTable = new BorderTable();

        Row bannerRow = mainTable.addRow();
        Cell bannerCell = bannerRow.addCell();
        bannerCell.addElement("<img src=\"http://www.hexacta.com/site/graphics/main/main_planet.jpg\">");
        Cell contentCell = mainTable.addRow().addCell();

        Table infoTable = new Table();
        contentCell.addElement(infoTable);
        Row row = null;
        Cell cell = null;

        row = infoTable.addRow();
        cell = row.addCell();
        cell.setColSpan(2);
        cell.addElement("<br>");
        cell
                .addElement(emailHelper
                        .getStandardParagraph("To establish your new FlashRecruit site, please follow the directions on this email.<br>"));

        row = infoTable.addRow();
        cell = row.addCell();
        cell.setColSpan(2);
        cell.addElement("<br>");
        cell.addElement(emailHelper.getStandardParagraph("<b>Please note the following credentials:</b>"));

        row = infoTable.addRow();
        cell = row.addCell();
        cell.addElement(emailHelper.getStandardParagraph("Name"));
        cell = row.addCell();
        cell.addElement(emailHelper.getStandardParagraph(person.getName()));

        row = infoTable.addRow();
        cell = row.addCell();
        cell.addElement(emailHelper.getStandardParagraph("User Name"));
        cell = row.addCell();
        cell.addElement(emailHelper.getStandardParagraph(person.getUser().getUserName()));

        row = infoTable.addRow();
        cell = row.addCell();
        cell.addElement(emailHelper.getStandardParagraph("Password"));
        cell = row.addCell();
        String password = person.getUser().getPassword();
        PasswordEncryptor encryptor = new PasswordEncryptor();
        String encryptedPassword = null;
        if (person.getUser().getPasswordEncrypted()) {
            encryptedPassword = password;
            password = encryptor.decrypt(password);
        } else {
            encryptedPassword = encryptor.crypt(password);
        }
        cell.addElement(emailHelper.getStandardParagraph(password));

        row = infoTable.addRow();
        cell = row.addCell();
        cell.setColSpan(2);
        cell.addElement("<br>");
        cell.addElement(emailHelper.getStandardParagraph("<br><br><b>Click this link to establish your site:</b>"));

        row = infoTable.addRow();
        cell = row.addCell();
        cell.setColSpan(2);

        String href = "http://www.vectrics.com/site/main/hosted/status.do" + "?applicationId=" + application.getId()
                + "&code=" + encryptedPassword;
        cell.addElement(emailHelper.getStandardLink(href, href));

        row = infoTable.addRow();
        cell = row.addCell();
        cell.setColSpan(2);
        cell.setAlign("center");
        cell.addElement("<br><br>" + emailHelper.getSmallFont("Vectrics, Inc."));

        String html = mainTable.toString();
        log.info("HTML: \r\n" + html);
        mailMessage.setBody(html);
        mailMessage.setSubject("FlashRecruit Site Confirmation");
        mailMessage.setFromName(CoreServiceLocator.getConfiguration().getSystemEmailFromName(domain));
        mailMessage.setFromAddress(CoreServiceLocator.getConfiguration().getSystemEmailFromAddress(domain));
        mailMessage.setContentType(MailMessage.CONTENT_HTML);
        try {
            NotificationManager.getInstance().sendMessage(person, mailMessage);
        } catch (Exception ex) {
            log.error("Exception sending email", ex);
        }
    }

}
